import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import "qrc:/qml/components" as Components
import "qrc:/qml/styles" as Styles

/**
 * @brief 仿真任务创建对话框
 * @details 用于快速创建仿真测试任务
 */
Components.CustomDialog {
    id: root
    title: qsTr("创建仿真任务")
    width: 480
    height: 500

    // 外部接口
    property var vehicleListModel: null
    property var taskViewModel: null

    signal taskCreated(string chainId)

    // 内部状态
    property bool isValid: targetStationField.text.length > 0

    contentItem: ColumnLayout {
        spacing: Styles.Theme.spacingNormal

        // ==================== 任务类型 ====================
        GroupBox {
            Layout.fillWidth: true
            title: qsTr("任务类型")

            background: Rectangle {
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusSmall
            }

            RowLayout {
                anchors.fill: parent
                spacing: Styles.Theme.spacingSmall

                Repeater {
                    model: [
                        { type: "move", text: qsTr("移动任务"), icon: "🚛", color: Styles.Theme.primary },
                        { type: "charge", text: qsTr("充电任务"), icon: "🔋", color: Styles.Theme.warning },
                        { type: "park", text: qsTr("泊车任务"), icon: "🅿️", color: Styles.Theme.info }
                    ]

                    delegate: Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 80
                        radius: Styles.Theme.radiusNormal
                        color: taskTypeGroup.checkedButton && taskTypeGroup.checkedButton.text === modelData.type ?
                               modelData.color : "transparent"
                        border.color: modelData.color
                        border.width: 2

                        ColumnLayout {
                            anchors.centerIn: parent
                            spacing: 4

                            Text {
                                text: modelData.icon
                                font.pixelSize: 32
                                Layout.alignment: Qt.AlignHCenter
                            }

                            Text {
                                text: modelData.text
                                color: taskTypeGroup.checkedButton && taskTypeGroup.checkedButton.text === modelData.type ?
                                       Styles.Theme.textOnPrimary : Styles.Theme.textPrimary
                                font.pixelSize: Styles.Theme.fontSizeSmall
                                font.weight: Font.Bold
                                Layout.alignment: Qt.AlignHCenter
                            }
                        }

                        RadioButton {
                            id: radioButton
                            anchors.fill: parent
                            text: modelData.type
                            visible: false
                            ButtonGroup.group: taskTypeGroup
                            checked: index === 0
                        }

                        MouseArea {
                            anchors.fill: parent
                            cursorShape: Qt.PointingHandCursor
                            onClicked: radioButton.checked = true
                        }
                    }
                }

                ButtonGroup {
                    id: taskTypeGroup
                }
            }
        }

        // ==================== 车辆选择 ====================
        GroupBox {
            Layout.fillWidth: true
            title: qsTr("车辆选择")

            background: Rectangle {
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusSmall
            }

            ColumnLayout {
                anchors.fill: parent
                spacing: Styles.Theme.spacingSmall

                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("目标车辆")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        Layout.preferredWidth: 80
                    }

                    Components.CustomComboBox {
                        id: vehicleCombo
                        Layout.fillWidth: true
                        model: getVehicleList()
                        currentIndex: 0
                    }
                }

                CheckBox {
                    id: autoSelectCheckbox
                    text: qsTr("自动选择最佳车辆（根据位置和电量）")
                    checked: false
                    font.pixelSize: Styles.Theme.fontSizeSmall

                    onCheckedChanged: {
                        vehicleCombo.enabled = !checked
                    }
                }
            }
        }

        // ==================== 任务参数 ====================
        GroupBox {
            Layout.fillWidth: true
            title: qsTr("任务参数")

            background: Rectangle {
                color: Styles.Theme.backgroundAlternate
                border.color: Styles.Theme.border
                border.width: 1
                radius: Styles.Theme.radiusSmall
            }

            ColumnLayout {
                anchors.fill: parent
                spacing: Styles.Theme.spacingSmall

                // 目标站点
                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall
                    visible: getSelectedTaskType() === "move" || getSelectedTaskType() === "park"

                    Text {
                        text: qsTr("目标站点*")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        Layout.preferredWidth: 80
                    }

                    TextField {
                        id: targetStationField
                        Layout.fillWidth: true
                        placeholderText: qsTr("例: LM90")
                        color: Styles.Theme.textPrimary
                        background: Rectangle {
                            color: Styles.Theme.surface
                            border.color: targetStationField.activeFocus ? Styles.Theme.primary : Styles.Theme.border
                            border.width: 1
                            radius: Styles.Theme.radiusSmall
                        }
                    }

                    Components.ActionButton {
                        text: qsTr("📍")
                        buttonType: "secondary"
                        width: 36
                        height: 36
                        enabled: false  // TODO: 地图拾取功能
                        ToolTip.visible: hovered
                        ToolTip.text: qsTr("从地图选取站点")
                    }
                }

                // 楼层
                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall
                    visible: getSelectedTaskType() === "move"

                    Text {
                        text: qsTr("目标楼层")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        Layout.preferredWidth: 80
                    }

                    SpinBox {
                        id: floorSpinBox
                        from: 1
                        to: 10
                        value: 2
                        editable: true
                    }
                }

                // 充电目标电量
                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall
                    visible: getSelectedTaskType() === "charge"

                    Text {
                        text: qsTr("目标电量")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        Layout.preferredWidth: 80
                    }

                    Slider {
                        id: targetBatterySlider
                        Layout.fillWidth: true
                        from: 50
                        to: 100
                        value: 100
                        stepSize: 10
                    }

                    Text {
                        text: targetBatterySlider.value.toFixed(0) + "%"
                        color: Styles.Theme.success
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        font.weight: Font.Bold
                        Layout.preferredWidth: 50
                    }
                }

                // 优先级
                RowLayout {
                    Layout.fillWidth: true
                    spacing: Styles.Theme.spacingSmall

                    Text {
                        text: qsTr("任务优先级")
                        color: Styles.Theme.textPrimary
                        font.pixelSize: Styles.Theme.fontSizeNormal
                        Layout.preferredWidth: 80
                    }

                    Components.CustomComboBox {
                        id: priorityCombo
                        Layout.fillWidth: true
                        model: [qsTr("普通"), qsTr("高"), qsTr("紧急")]
                        currentIndex: 0
                    }
                }
            }
        }

        Item {
            Layout.fillHeight: true
        }

        // ==================== 按钮栏 ====================
        RowLayout {
            Layout.fillWidth: true
            spacing: Styles.Theme.spacingSmall

            Item {
                Layout.fillWidth: true
            }

            Components.ActionButton {
                text: qsTr("取消")
                buttonType: "secondary"
                onClicked: root.close()
            }

            Components.ActionButton {
                text: qsTr("创建任务")
                buttonType: "primary"
                enabled: isValid
                onClicked: createTask()
            }
        }
    }

    // ==================== 辅助函数 ====================

    function getVehicleList() {
        if (!vehicleListModel) return [qsTr("无可用车辆")]

        let vehicles = []
        for (let i = 0; i < vehicleListModel.rowCount(); i++) {
            let agv = vehicleListModel.getAgvData(i)
            vehicles.push(`AGV${agv.agvNumber} - ${agv.agvName}`)
        }

        if (vehicles.length === 0) {
            vehicles.push(qsTr("无可用车辆"))
        }

        return vehicles
    }

    function getSelectedTaskType() {
        return taskTypeGroup.checkedButton ? taskTypeGroup.checkedButton.text : "move"
    }

    function getSelectedVehicleNumber() {
        if (autoSelectCheckbox.checked) return -1

        let text = vehicleCombo.currentText
        let match = text.match(/AGV(\d+)/)
        return match ? parseInt(match[1]) : -1
    }

    function createTask() {
        if (!taskViewModel) {
            console.error("TaskViewModel not available")
            return
        }

        const taskType = getSelectedTaskType()
        const agvNumber = getSelectedVehicleNumber()
        let chainId = ""

        switch (taskType) {
            case "move":
                chainId = taskViewModel.createMoveTask(
                    targetStationField.text,
                    floorSpinBox.value,
                    agvNumber
                )
                break

            case "charge":
                chainId = taskViewModel.createChargeTask(
                    agvNumber,
                    "",  // 自动选择充电点
                    targetBatterySlider.value
                )
                break

            case "park":
                chainId = taskViewModel.createParkTask(
                    agvNumber,
                    targetStationField.text
                )
                break
        }

        if (chainId) {
            taskCreated(chainId)
            root.close()
        }
    }

    function reset() {
        targetStationField.text = ""
        floorSpinBox.value = 2
        targetBatterySlider.value = 100
        priorityCombo.currentIndex = 0
        autoSelectCheckbox.checked = false
        vehicleCombo.currentIndex = 0
    }

    Component.onCompleted: {
        // 默认选择第一个任务类型
        if (taskTypeGroup.buttons.length > 0) {
            taskTypeGroup.buttons[0].checked = true
        }
    }
}
